<template>
  <div>
    <vxe-toolbar ref="xToolbar1" custom print>
      <template #buttons>
        <vxe-button icon="fa fa-plus" @click="insertEvent(-1)">新增</vxe-button>
        <vxe-button icon="fa fa-save" @click="saveEvent">保存</vxe-button>
        <vxe-button icon="fa fa-save" @click="deletedata"
          >删除选中项(仅限当页)</vxe-button
        >
        <vxe-input v-model="filterName1" type="search" placeholder="全表搜索" @keyup="searchEvent1"></vxe-input>
        <vxe-button @click="exportCurrDataEvent4">导出当前页</vxe-button>
      </template>
    </vxe-toolbar>
    <vxe-table
      keep-sourc:true
      :edit-config="{
        trigger: 'dblclick',
        mode: 'cell',
        icon: 'fa fa-pencil',
        showStatus: true,
      }"
      ref="xTable"
      border
      resizable
      highlight-hover-row
      highlight-current-row
      :data="tableData"
      :mouse-config="{selected: true}"
      :keyboard-config="{isArrow: true, isDel: true, isEnter: true, isTab: true, isEdit: true, isChecked: true}"
    >
      <vxe-column type="checkbox" width="60"></vxe-column>
      <vxe-column field="id" title="序号" width="80"></vxe-column>
      <vxe-column
        field="name"
        title="名字"
        :edit-render="{ name: 'input', defaultValue: '默认的名字' }"
        :filters="[{ label: '包含 6', value: '6' }, { label: '包含 4', value: '4' }]"
        :filter-method="filterNameMethod"
        sortable
      ></vxe-column>
      <vxe-column
        field="sex"
        title="性别"
        :formatter="formatterSex"
        :edit-render="{ name: 'input' }"
        sortable
        :filters="[{ label: '男', value: 1 }, { label: '女', value: 0}]"
        :filter-method="filterSexMethod"
      ></vxe-column>
      <vxe-column
        field="age"
        title="年龄"
        :filters="[{ data: '' }]" 
        :filter-method="filterAgeMethod" 
        :filter-recover-method="filterAgeRecoverMethod"
        sortable
        :edit-render="{ name: 'input', defaultValue: '请输入年龄' }"
      >
        <template #filter="{ $panel, column }">
          <template v-for="(option, index) in column.filters">
            <input class="my-input" type="type" :key="index" v-model="option.data" @input="$panel.changeOption($event, !!option.data, option)" @keyup.enter="$panel.confirmFilter()" placeholder="按回车确认筛选">
          </template>
        </template>
      </vxe-column>
      <vxe-column
        field="address"
        title="地址"
        show-overflow
        :edit-render="{ name: 'input', defaultValue: '默认地址' }"
      ></vxe-column>
      <vxe-column title="操作" width="60" show-overflow>
        <template #default="{ row }">
          <vxe-button @click="editEvent(row)">
            <i class="vxe-icon--edit-outline"></i
          ></vxe-button>
        </template>
      </vxe-column>
    </vxe-table>

    <!-- 分页 -->
    <vxe-pager
      align="right"
      :current-page.sync="page1.currentPage"
      :page-size.sync="page1.pageSize"
      :total="page1.totalResult"
      :page-sizes="page1.pagesize"
      @page-change="pagechange"
    >
    </vxe-pager>

    <!-- 修改框 -->
    <vxe-modal
      ref="xModal"
      v-model="showEdit"
      title="编辑&保存"
      width="800"
      resize
      destroy-on-close
    >
      <template #default>
        <vxe-form
          :data="formData"
          :rules="formRules"
          title-align="right"
          title-width="100"
          @submit="submitEvent"
        >
          <vxe-form-item
            title="基本信息"
            span="24"
            title-align="left"
            title-width="200px"
            :title-prefix="{ icon: 'fa fa-address-card-o' }"
          ></vxe-form-item>
          <vxe-form-item
            title="姓名"
            field="name"
            span="12"
            :item-render="{
              name: 'input',
              attrs: { placeholder: '请输入名称' },
            }"
          ></vxe-form-item>
          <vxe-form-item
            title="昵称"
            field="nickname"
            span="12"
            :item-render="{
              name: 'input',
              attrs: { placeholder: '请输入昵称' },
            }"
          ></vxe-form-item>
          <vxe-form-item
            title="权限"
            field="role"
            span="12"
            :item-render="{
              name: 'input',
              attrs: { placeholder: '请输入角色' },
            }"
          ></vxe-form-item>
          <vxe-form-item
            title="性别"
            field="sex"
            span="12"
            :item-render="{ name: '$select', options: sexList }"
          ></vxe-form-item>
          <vxe-form-item
            title="年龄"
            field="age"
            span="12"
            :item-render="{
              name: 'input',
              attrs: { type: 'number', placeholder: '请输入年龄' },
            }"
          ></vxe-form-item>
          <vxe-form-item
            title="其他信息"
            span="24"
            title-align="left"
            title-width="200px"
            :title-prefix="{
              message: '请填写必填项',
              icon: 'fa fa-info-circle',
            }"
          ></vxe-form-item>
          <vxe-form-item
            title="数字"
            field="num"
            span="12"
            :item-render="{
              name: 'input',
              attrs: { type: 'number', placeholder: '请输入数值' },
            }"
          ></vxe-form-item>
          <vxe-form-item
            :edit-render="{ name: '$input', props: { type: 'date' } }"
            title="时间"
            field="date3"
            span="12"
            :item-render="{
              name: '$input',
              props: { type: 'date', placeholder: '请选择日期' },
            }"
          ></vxe-form-item>
          <vxe-form-item
            title="地址"
            field="address"
            span="24"
            :title-suffix="{
              message: '啦啦啦，就是这么强大！！！',
              icon: 'fa fa-question-circle',
            }"
            :item-render="{
              name: 'textarea',
              attrs: { placeholder: '请输入地址' },
            }"
          ></vxe-form-item>
          <vxe-form-item align="center" span="24">
            <template #default>
              <vxe-button type="submit" status="primary">保存</vxe-button>
              <vxe-button type="reset">重置</vxe-button>
              <vxe-button @click="$refs.xModal.close()">取消</vxe-button>
            </template>
          </vxe-form-item>
        </vxe-form>
      </template>
    </vxe-modal>
  </div>
</template>
<script>
import data from "../resource/Orderlist";
import XEUtils from 'xe-utils'
export default {
  data() {
    return {
      filterName1:'',
      addsrouse: {},
      page1: {
        currentPage: 1,
        pageSize: 10,
        totalResult: 0,
        pagesize: [2, 4, 6, 8, 10],
      },
      selectRow: null,
      showEdit: false,
      sexList: [
        { label: "", value: "" },
        { label: "女", value: "0" },
        { label: "男", value: "1" },
      ],
      formData: null,
      formRules: {
        name: [
          { required: true, message: "请输入名称" },
          { min: 3, max: 20, message: "长度在 3 到 5 个字符" },
        ],
        nickname: [{ required: true, message: "请输入昵称" }],
        sex: [{ required: true, message: "请选择性别" }],
      },
      tableData: data.tableDatas,
    };
  },
  methods: {
    formatterSex({ cellValue }) {
      const item = this.sexList.find((item) => item.value === cellValue);
      return item ? item.label : "";
    },
    editEvent(row) {
      console.log(row);
      this.formData = {
        name: row.name,
        nickname: row.nickname,
        role: row.role,
        sex: row.sex,
        age: row.age,
        num: row.num,
        date3: row.date3,
        address: row.address,
      };
      this.selectRow = row;
      this.showEdit = true;
    },
    submitEvent(data, $event) {
      console.log(data, $event);
      this.showEdit = false;
      this.$XModal.message({ content: "保存成功", status: "success" });
      Object.assign(this.selectRow, this.formData);
    },
    pagechange(type) {
      const { pageSize, currentPage } = type;
      console.log(pageSize, currentPage);
      const newTableData = data.tableDatas.slice(
        pageSize * currentPage - pageSize,
        pageSize * currentPage
      );
      this.tableData = newTableData;
    },
    async insertEvent(row) {
      const $table = this.$refs.xTable;
      const record = {
        id: "id系统自动生成无法修改",
        sex: "1",
        date3: "2021-01-01",
        address: "默认地址",
        age: 18,
        name: "默认名字",
      };
      this.addsrouse = record;
      const { row: newRow } = await $table.insertAt(record, row);
      await $table.setActiveCell(newRow, "sex");
    },
    saveEvent() {
      data.tableDatas.push(this.addsrouse);
      const $table = this.$refs.xTable;
      const { insertRecords, removeRecords, updateRecords } =
        $table.getRecordset();
      if (insertRecords.length != 0) {
        this.page1.totalResult += insertRecords.length;
      }
      this.$XModal.alert(
        `新增加个数=${insertRecords.length} 删除个数=${removeRecords.length} 更新个数=${updateRecords.length}`
      );
    },
    deletedata() {
      const $table = this.$refs.xTable;
      const selectRecords = $table.getCheckboxRecords();
      console.log("selectRecords", selectRecords);
      for (let j = 0; j < selectRecords.length; j++) {
        for (let i = 0; i < data.tableDatas.length; i++) {
          if (data.tableDatas[i].id === selectRecords[j].id) {
            data.tableDatas.splice(i, 1);
          }
        }
      }
      console.log(data.tableDatas)
      this.page1.totalResult -= selectRecords.length
    },
    searchEvent1() {
      const filterName = XEUtils.toValueString(this.filterName1).trim().toLowerCase()
      console.log(filterName)
      if (filterName) {
        const filterRE = new RegExp(filterName, 'gi')
        console.log('filterRE',filterRE)
        const searchProps = ['name', 'role', 'age', 'address']
        const rest = this.tableData.filter(item => searchProps.some(key => XEUtils.toValueString(item[key]).toLowerCase().indexOf(filterName) > -1))
        console.log('rest',rest)
        this.tableData = rest.map(row => {
          const item = Object.assign({}, row)
          searchProps.forEach(key => {
            item[key] = XEUtils.toValueString(item[key]).replace(filterRE, match => `${match}`)
          })
          return item
        })
        this.page1.totalResult = this.tableData.length
      } else {
        this.tableData =  data.tableDatas
      }
    },
    filterNameMethod ({ value, row }) {
      console.log('姓名',value,row)
      return XEUtils.toValueString(row.name).toLowerCase().indexOf(value) > -1
    },
    filterSexMethod({ value, row }){
      console.log('性别',value,row)
      return XEUtils.toValueString(row.sex).toLowerCase().indexOf(value) > -1
    },
    filterAgeMethod ({ option, row }) {
      return row.age === Number(option.data)
    },
    filterAgeRecoverMethod ({ option }) {
      // 如果是自定义筛选模板，当为点击确认时，该选项将被恢复为默认值
      option.data = ''
    },
    exportCurrDataEvent4 () {
      this.$refs.xTable.exportData({  
        filename: 'data',
        type: 'csv',
        isHeader: true,
        isFooter: true
      })
    },
  },
  created() {
    this.page1.totalResult = this.tableData.length;
    // this.searchEvent1()
  },
};
</script>
<style scoped>
 .keywordlighten {
  color: #000;
  background-color: #FFFF00;
}
.my-select {
  margin: 10px;
  width: 100px;
  height: 32px;
}
.my-input {
  margin: 10px;
  width: 140px;
  height: 32px;
}
</style>